package br.com.abelha.manager.ws;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import br.com.abelha.manager.entity.FormA;


/**
 * @author dalsonsouza
 */

public class RequestAbelhaService {
	
	private String userA;
	private String passA;
	private String uriA;
	
	private File xml;
	private int timeout;
	
	private boolean ultimo;
	
	public RequestAbelhaService user(String user) {
		this.userA = user;
		return this;
	}

	public RequestAbelhaService pass(String pass) {
		this.passA = pass;
		return this;
	}

	public RequestAbelhaService uri(String uri) {
		this.uriA = uri;
		return this;
	}
	
	public RequestAbelhaService xml(File xml) {
		this.xml = xml;
		return this;
	}
	
	public RequestAbelhaService timeout(int timeout) {
		this.timeout = timeout;
		return this;
	}
	
	private List<FormA> listaParaSalvar;
	private FormA auxiliarParaLista;

	public List<FormA> requestColmeiaServer() {
		
		try {

			HttpClient client = new DefaultHttpClient();
			String getURL = this.uriA;

			StringBuilder uriBuilder = new StringBuilder(getURL);
			//uriBuilder.append("?strLogin=" + this.userA);
			//uriBuilder.append("&strSenha=" + this.passA);
			
			HttpGet get = new HttpGet(uriBuilder.toString());
			
			HttpResponse responseGet = client.execute(get);
			HttpEntity resEntityGet = responseGet.getEntity();
			
			String asd = EntityUtils.toString(resEntityGet);
			listaParaSalvar = new ArrayList<FormA>();
			
			try {
				
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		        factory.setNamespaceAware(true);
		        XmlPullParser xpp = factory.newPullParser();
				
		        xpp.setInput( new StringReader (asd) );
		        int eventType = xpp.getEventType();
		        
		        ultimo = false;
		        auxiliarParaLista = new FormA();
		        
		        while (eventType != XmlPullParser.END_DOCUMENT) {
		        	
		        	if(eventType == XmlPullParser.START_DOCUMENT) {
		        		//System.out.println("Start document");
		        	} else if(eventType == XmlPullParser.START_TAG) {
		        		
		        		//System.out.println("NOME  ============= " + xpp.getName());
		        		
		        		String nomeCampo = xpp.getName();
		        		
		        		xpp.next();
		        		eventType = xpp.getEventType();
		        		if(eventType == XmlPullParser.TEXT){
		        			//System.out.println("TEXTO ============= " + xpp.getText());
		        		}
		        		
		        		String valorCampo = xpp.getText();
		        		nomeDoCampoEstaNoFormaA(nomeCampo, valorCampo);
		        			
		        		
		        	} else if(eventType == XmlPullParser.END_TAG) {
		        		//System.out.println("ULTIMO ======== "+ xpp.getName());
		        		
		        	} else if(eventType == XmlPullParser.TEXT) {
		        	}
		        	eventType = xpp.next();
		        }
		        
		        
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		
		} catch (Exception e) {
			e.printStackTrace();
		}

		return listaParaSalvar;

	}
	
	public boolean nomeDoCampoEstaNoFormaA(String nome, String valor){
		
		FormA formA = new FormA();
		Object clazz = formA; 
		Class<?> c = clazz.getClass();
		
		Field[] fields = c.getDeclaredFields();
		
		FormA aux = new FormA();
		
		try {
			
			for (int i = 0; i < fields.length; i++) {
				
				if (!Modifier.isStatic(fields[i].getModifiers())) {
					
					String nomeCampoClasse = fields[i].getName();
					
					if(nomeCampoClasse.equals(nome.toLowerCase())){
						
						fields[i].setAccessible(true);
						
						if(fields[i].getType().equals (Integer.class)){
							Integer a = new Integer(valor);
							fields[i].set(clazz, a);
							
							aux = (FormA) clazz;
							
							Object clazz2 = auxiliarParaLista; 
							Class<?> c2 = clazz2.getClass();
							
							Field[] fields2 = c2.getDeclaredFields();
							
							for (int j = 0; j < fields2.length; j++) {
								
								fields2[i].setAccessible(true);
								
								//Mesmo valor, insere...
								if(fields[i].getName().equals(fields2[j].getName())){
									
									fields2[j].set(clazz2, a);
									
								}
								
							}
							
						}else if(fields[i].getType().equals (Long.class)){
							Long a = new Long(valor);
							fields[i].set(clazz, a);
							
							aux = (FormA) clazz;
							
							Object clazz2 = auxiliarParaLista; 
							Class<?> c2 = clazz2.getClass();
							
							Field[] fields2 = c2.getDeclaredFields();
							
							for (int j = 0; j < fields2.length; j++) {
								
								fields2[i].setAccessible(true);
								
								//Mesmo valor, insere...
								if(fields[i].getName().equals(fields2[j].getName())){
									
									fields2[j].set(clazz2, a);
									
								}
								
							}
							
						}else{
							
							fields[i].set(clazz, valor);
							
							aux = (FormA) clazz;
							
							Object clazz2 = auxiliarParaLista; 
							Class<?> c2 = clazz2.getClass();
							
							Field[] fields2 = c2.getDeclaredFields();
							
							for (int j = 0; j < fields2.length; j++) {
								
								fields2[i].setAccessible(true);
								
								//Mesmo valor, insere...
								if(fields[i].getName().equals(fields2[j].getName())){
									
									fields2[j].set(clazz2, valor);
									
								}
								
							}
							
							
						}
					}
				}
				
			}
			
			//Ultimo item da lista... grava no Array
			if(nome.equals("MEIO_TRANSP_CARROCA")){
				listaParaSalvar.add(auxiliarParaLista);
				auxiliarParaLista = new FormA();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
		
	}
	
	
	public String post() throws IOException {
		
		String getURL = this.uriA;
		int timeout  = this.timeout;
		
	    HttpParams httpParameters = new BasicHttpParams();  
	    HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);  
	    HttpConnectionParams.setSoTimeout(httpParameters, timeout);  
	  
	    HttpPost httppost = new HttpPost(getURL);  
	    DefaultHttpClient httpClient = new DefaultHttpClient();  
	    
	    String res = null;
	    try {
	        // open the file for reading
	        InputStream in = new FileInputStream(this.xml.getAbsoluteFile());
	     
	        if (in != null) {
	    	    // prepare the file for reading
	    	     InputStreamReader input = new InputStreamReader(in);
	    	     BufferedReader buffreader = new BufferedReader(input);

	    	      res = buffreader.readLine();
	    	      in.close();
	              }
	             
	      } catch (java.io.FileNotFoundException e) {
	        // do something if the myfilename.txt does not exits
	      }
	    
	    StringEntity se = new StringEntity(res, "UTF-8");
	    
	    httppost.setEntity(se);  
	    httpClient.setParams(httpParameters); //eu seto os params aqui... tinha me esquecido disso!  
	  
	    HttpResponse response = httpClient.execute(httppost);  
	    HttpEntity entity = response.getEntity();  
	    InputStream is = entity.getContent();  
	  
	    if (is == null) {  
	        return "";  
	    }  
	   
	    return null;
	}  
	
	public static String getValue(Element item, String str) {		
		NodeList n = item.getElementsByTagName(str);		
		return RequestAbelhaService.getElementValue(n.item(0));
	}
	
	public final static String getElementValue( Node elem ) {
	     Node kid;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
	                 if( kid.getNodeType() == Node.TEXT_NODE  ){
	                     return kid.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }

	public String getUserA() {
		return userA;
	}

	public void setUserA(String userA) {
		this.userA = userA;
	}

	public String getPassA() {
		return passA;
	}

	public void setPassA(String passA) {
		this.passA = passA;
	}

	public String getUriA() {
		return uriA;
	}

	public void setUriA(String uriA) {
		this.uriA = uriA;
	}

}
